package com.labot.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.labot.dao.MailTemplateDao;
import com.labot.model.MailTemplate;
import com.labot.types.MailType;

/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve Config objects.
 *
 * @author Ing. Enrique Barbeito
*/
@Repository("mailTemplateDao")
public class MailTemplateDaoHibernate extends GenericDaoHibernate<MailTemplate, Long> implements MailTemplateDao {

    /**
     * Constructor that sets the entity to User.class.
     */
    public MailTemplateDaoHibernate() {
        super(MailTemplate.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public MailTemplate getMailTemplate(MailType type) {
        List<MailTemplate> m = getSession().createCriteria(MailTemplate.class).add(Restrictions.eq("name", type)).list();
        if (m.isEmpty()) {
            return null;
        } else {
            return (MailTemplate) m.get(0);
        }
    }
    
    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<MailTemplate> getAll() {
        Query qry = getSession().createQuery("from MailTemplate c order by upper(c.name)");
        return qry.list();
    }

    /**
     * {@inheritDoc}
     */
    public MailTemplate saveMailTemplate(MailTemplate mail) {
        if (log.isDebugEnabled()) {
            log.debug("MailTemplate's id: " + mail.getId());
        }
        getSession().saveOrUpdate(mail);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getSession().flush();
        return mail;
    }

    /**
     * Overridden simply to call the saveUser method. This is happening
     * because saveUser flushes the session and saveObject of BaseDaoHibernate
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public MailTemplate save(MailTemplate mailTemplate) {
        return this.saveMailTemplate(mailTemplate);
    }


	@Override
	public void excuteBatch(String hql) {
		Query qry = getSession().createQuery(hql);
		qry.executeUpdate();		
	}

}
